
# from info import redis_store
from datetime import datetime

from flask import current_app, session
from info import redis_store, db

from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue
from flask import make_response, request, jsonify
import json
import re
import random

# 退出登陆
# 请求路径 /passport/logout
# 请求方式 POST
# 请求参数 无
# 返回值:errno,errmsg
@passport_blue.route('/logout', methods=['GET', 'POST'])
def logout():
    #1 清除session信息
    session.pop('user_id', None)
    session.pop('nick_name', None)

    #2 返回状态
    return jsonify(errno=RET.OK,errmsg='退出成功')


# 登陆用户
# 请求路径 /passport/login
# 请求方式:POST
# 请求参数 mobile,password
# 返回值 errno errmsg
@passport_blue.route('/login', methods=['POST'])
def login():
    # 1 获取参数
    mobile = request.json.get('mobile')
    password = request.json.get('password')

    # 2 校验参数
    # 2.1 根据手机号,获取用户对象,并判断是否存在
    try:
        user = User.query.filter(User.mobile == mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询用户失败')


    #2.2 判断密码是否正确
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg='密码错误')

    #3 动态保持
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name

    # try:
    #     user.last_login = datetime.now()
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    user.last_login = datetime.now()

    # 4 返回响应
    return jsonify(errno=RET.OK, errmsg='登陆成功')


@passport_blue.route('/register', methods=['POST'])
def register():
    # 1 获取参数
    dict_data = request.json
    mobile = dict_data.get('mobile')
    sms_code = dict_data.get('sms_code')
    password = dict_data.get('password')

    # 2 校验参数
    # 2.1 判断用户是否存在
    count = User.query.filter(User.mobile == mobile).count()
    if count > 0:
        return jsonify(errno=RET.DATAERR, errmsg='用户已存在')
    # 2.2 短信验证码的正确性
    redis_sms_code = redis_store.get('sms_code:%s'%mobile)

    if not redis_sms_code:
        return jsonify(error=RET.DATAERR,errmsg='短信验证码过期')

    if sms_code != redis_sms_code:
        return jsonify(errno=RET.DATAERR,errmsg='短信验证码填写错误')

    # 3 创建用户对象入库
    try:
        user = User()
        user.nick_name = mobile
        user.password = password
        user.mobile = mobile

        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.OK, errmsg='注册失败')

    return jsonify(errno=RET.OK, errmsg='注册失败')


@passport_blue.route('/sms_code', methods=['POST'])
def sms_code():
    # 1 获取参数
    json_data = request.data.decode()
    dict_data = json.loads(json_data)
    mobile = dict_data.get("mobile")
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")

    # 2 校验参数
    # 2.1 校验是否为空
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不全')

    # 2.2
    if not re.match(r'1[3-9]\d{9}', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式有误")

    redis_image_code = redis_store.get("image_code:%s"%image_code_id)
    if not redis_image_code:
        return jsonify(errno=RET.PARAMERR, errmsg="图片验证码过期")
    redis_store.delete("image_code:%s" % image_code_id)

    if image_code.lower() != redis_image_code.lower():
        return jsonify(errno=RET.DATAERR, errmsg="图片验证码填写错误")

    # 3 发送短信
    sms_code = "%06d" % random.randint(0, 999999)
    # ccp = CCP()
    # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
    # if result == -1:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送失败")
    current_app.logger.debug('sms_code=%s'%sms_code)
    redis_store.set("sms_code:%s" % mobile, sms_code, 300)
    # 4 返回响应
    return jsonify(errno=RET.OK, errmsg="发送成功")

@passport_blue.route('/image_code')
def image_code():

    # 1 获取参数,cur_id
    cur_id = request.args.get('cur_id')
    pre_id = request.args.get("pre_id")

    # 2 校核参数
    if not cur_id:
        return '参数不全'
    # 2,1 判断上一个图片验证码编号是否存在,存在则删除
    if pre_id:
        redis_store.delete("image_code:%s" % pre_id)

    # 3 生成图片验证码
    name, text, image_code = captcha.generate_captcha()

    # 4 存储到redis中
    redis_store.set('image_code:%s'%cur_id, text, 300)

    # 5 返回图片验证码
    response = make_response(image_code)
    response.headers['Content-Type'] = 'image/png'
    return response


